package com.fker.opt;

import static com.fker.opt.AdStrategy.arrayCoords;

import android.os.Build;
import android.view.InputDevice;
import android.view.MotionEvent;

import java.util.Random;

 class MotionEventProxy {

    public MotionEvent createMotionEvent(long downTime, long eventTime, int action, float x, float y, float size) {
        MotionEvent.PointerProperties[] pointerProperties = arrayProperties(1);
        pointerProperties[0].clear();
        pointerProperties[0].id = 0;
        pointerProperties[0].toolType = MotionEvent.TOOL_TYPE_FINGER;

        MotionEvent.PointerCoords[] pointerCoords = arrayCoords(1);
        pointerCoords[0].clear();
        pointerCoords[0].x = x;
        pointerCoords[0].y = y;
        pointerCoords[0].pressure = 1.0f;
        if (size <= 0) {
            size = getRandom(2, 100) / 101f;
        }
        pointerCoords[0].size = size;
        return MotionEvent.obtain(downTime, eventTime, action, 1, pointerProperties, pointerCoords, 0, 0, 1.0f, 1.0f,
                getInputDeviceId(InputDevice.SOURCE_TOUCHSCREEN), 0, InputDevice.SOURCE_TOUCHSCREEN, 0);
    }

    public static MotionEvent.PointerProperties[] arrayProperties(int size) {
        MotionEvent.PointerProperties[] array = new MotionEvent.PointerProperties[size];
        for (int i = 0; i < size; i++) {
            array[i] = new MotionEvent.PointerProperties();
        }
        return array;
    }

    public int getRandom(int min, int max) {
        Random random = new Random();
        int result = random.nextInt(max) % (max - min + 1) + min;
        return result;
    }

    private static int getInputDeviceId(int sourceTouchscreen) {
        int result = 0;
        int[] deviceIds = InputDevice.getDeviceIds();
        for (int deviceid : deviceIds) {
            InputDevice inputDevice = InputDevice.getDevice(deviceid);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                if (inputDevice.supportsSource(sourceTouchscreen)) {
                    return deviceid;
                }
            }
        }
        return result;
    }

}
